<template>
  <div>
    <el-row>
      <el-col :span="6" class="pull-right" style="margin-bottom: 20px;margin-right: 51px">
        <el-form ref="searchForm" class="el-form-col" >
          <el-input placeholder="请输入商品名称" clearable v-model="name">
            <el-button slot="append" icon="el-icon-search" native-type="submit" @click.prevent="getProducts"></el-button>
          </el-input>
        </el-form>
      </el-col>
      <el-col :span="24" v-if="!isEditPicture">
        <div class="a-product-show-box" v-for="(item, index) in productArr" :key="index" :title="item.pictureName">
          <div class="product-show-img-box">
            <div class="product-img-b">
              <imgViewer :imgArr="item.picture"></imgViewer>
            </div>
            <div class="product-img-num">{{item.picture.length}}图</div>
            <div class="product-img-name">
              <editProductName :item="item"
                               :analysisData.sync="item.isEdit"
                               :pictureName.sync="item.pictureName"
                               @saveImg="saveImg"
                               ref="editProductName" v-if="item.isEdit"
              >
              </editProductName>
              <span v-if="!item.isEdit">{{item.pictureName}}</span>
              <i class="product-img-edit el-icon-edit pull-right" @click="edit(item)" v-if="!item.isEdit"></i>
            </div>
            <div class="product-img-operation">
              <span class="blue-color text-cursor" @click="editPicture(item)">管理图片</span>
              <span class="blue-color text-cursor" @click="del(item)">删除</span>
            </div>
          </div>
        </div>
        <div class="a-product-show-box" v-if="activeMenuData.minddleClassCode">
          <div class="product-show-img-box">
            <upload-image :allShowUploadBox="true" @file="addImg" :showImageList="false" :multiple="false" :drag="false" :listItemStyle="{width: '182px', height: '176px'}">
              <img src="/static/images/addProduct.png" style="width: 182px;height: 176px" alt="">
            </upload-image>
          </div>
        </div>
        <div class="noProduct-box" v-if="!activeMenuData.minddleClassCode">
          <img src="/static/images/faHuoBao/minions01.png" alt="">
          <p style="font-size: 18px;font-weight: bold;color: #444">选择产品类目 管理我的产品</p>
        </div>
      </el-col>
      <el-col :span="24" v-if="isEditPicture">
        <div class="a-product-show-box" v-for="(item, index) in pictureArr" :key="index" :title="item.pictureName">
          <div class="product-show-img-box">
            <div class="product-img-b">
              <imgViewer :imgArr="item.picture"></imgViewer>
            </div>
            <div class="product-img-name">
              <span>{{item.pictureName}}</span>
            </div>
            <div class="product-img-operation">
              <span class="blue-color text-cursor" @click="delPicture(item)">删除</span>
            </div>
          </div>
        </div>
        <div class="a-product-show-box" v-if="activeMenuData.minddleClassCode && pictureArr.length < 4">
          <div class="product-show-img-box">
            <upload-image :allShowUploadBox="true" @file="addPicture" :showImageList="false" :multiple="false" :drag="false" :listItemStyle="{width: '182px', height: '176px'}">
              <img src="/static/images/addPicture.png" style="width: 182px;height: 176px" alt="">
            </upload-image>
          </div>
        </div>
        <div class="noProduct-box" v-if="!activeMenuData.minddleClassCode">
          <img src="/static/images/faHuoBao/minions01.png" alt="">
          <p style="font-size: 18px;font-weight: bold;color: #444">选择产品类目 管理我的产品</p>
        </div>
      </el-col>
    </el-row>
    <el-row v-if="productArr.length">
      <el-col :span="24">
        <pagination class="pull-right" style="margin-right: 51px;margin-bottom: 20px"
                    :total-item="totalItem"
                    @sizeChange="sizeChange"
                    @pagination="pagination"
                    :per-item="params.pageSize"></pagination>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {bus} from '@/utils/bus'
import Pagination from '@/components/Pagination'
// import UploadImageItem from 'components/admin/product/UploadImageItem'
// import addProductTwoType from 'components/product/addProductTwoType'
import EditProductName from '@/views/fhb/product/EditProductName'
import {copy, dotData, confirm} from '@/utils'
import ImgViewer from '@/views/fhb/temporary/ImgViewer'

export default {
  name: 'productTwoType',
  components: {
    Pagination,
    // UploadImageItem,
    // addProductTwoType,
    EditProductName,
    ImgViewer
  },
  data() {
    return {
      params: {
        pageSize: 10,
        pageNum: 1
      },
      productArr: [],
      isEditPicture: false,
      pictureArr: [],
      thisItem: {},
      totalItem: 0,
      name: '',
      goodId: '',
      activeMenuData: {}
    }
  },
  created() {
    bus.$on('activeMenuValFHB', (classCode, refresh) => {
      console.log('classCode', classCode)
      this.activeMenuData = classCode
      if (refresh) {
        return
      } // 刷新界面不主动请求数据
      this.name = ''
      this.getProducts()
    })
  },
  methods: {
    sizeChange(size) {
      this.params.pageSize = size
      this.getProducts()
    },
    pagination(page) {
      this.params.pageNum = page
      this.getProducts()
    },
    getProducts() {
      this.isEditPicture = false
      this.params.middleCode = this.activeMenuData.minddleClassCode
      this.params.code = this.activeMenuData.bigClassCode
      this.params.name = this.name
      this.params.state = '2'
      if (this.name) {
        this.params.middleCode = ''
        this.params.code = ''
      }
      this.$ajax.table('/ms-fahuobao-order/FhbOrder/getDetailPic', this.params).then(response => {
        if (!response.success) {
          return
        }
        this.totalItem = response.totalItem
        let arr = copy(response.data, true)
        arr.forEach(item => {
          item.picture = item.picture.split(',')
          console.log('item', item)
          this.$set(item, 'isEdit', false)
        })
        this.productArr = arr
        console.log('this.productArr', this.productArr)
        bus.$emit('activeSubmenuValFHB', dotData(this.productArr, '[0].middleClassNo'))
        // 如果用户直接搜索，并且只有一个值时，在右边产品菜单里面锁定值
        // if (!this.activeMenuData.middleClassNo && this.productArr.length === 1) {
        //   bus.$emit('activeSubmenuValFHB', this.productArr[0].middleClassNo)
        // }
      })
    },
    saveImg(val, name) {
      this.saveImgPromise(val, name).then(response => {
        if (!name) {
          val.isEdit = true
        }
        this.getProducts()
      })
    },
    saveImgPromise(val, name) {
      return new Promise((resolve, reject) => {
        let obj = {}
        if (!name) { // 替换图片
          obj.goodId = val.goodId
          obj.goodPicture = val.goodPicture
        } else { // 更改产品名称
          obj.goodId = val.goodsBaseId
          obj.goodName = val.pictureName
        }
        obj.state = '1' // 1商家新增，2：后台新增
        this.$ajax.post('/ms-fahuobao-order/fhbGoodAdmin/editGoodType', obj).then(response => {
          if (response.success) {
            resolve(response.success)
          }
        })
      })
    },
    addImg(val) {
      let obj = {
        goodPicture: val.fileId,
        goodName: val.fileName,
        goodOneCode: this.activeMenuData.bigClassCode,
        goodTwoCode: this.activeMenuData.minddleClassCode,
        state: '1'
      }
      this.$ajax.post('/ms-fahuobao-order/fhbGoodAdmin/saveMerchantGoodPicture', obj).then(response => {
        if (response.success) {
          this.getProducts()
        }
      })
    },
    editPicture(item) {
      console.log('item', item)
      this.isEditPicture = true
      this.thisItem = item
      this.pictureArr = []
      this.searchPicture()
    },
    searchPicture() {
      let data = {}
      data.goodsBaseId = this.thisItem.goodsBaseId
      data.code = this.thisItem.bigClassNo || this.activeMenuData.bigClassCode
      data.middleCode = this.thisItem.middleClassNo || this.activeMenuData.minddleClassCode
      data.pageSize = 10
      data.pageNum = 1
      data.state = '2'
      this.$ajax.table('/ms-fahuobao-order/FhbOrder/getDetailPic', data).then(response => {
        let arr = copy(response.data, true)
        let _obj = arr.find(v => this.thisItem.goodsBaseId === v.goodsBaseId) || {}
        this.pictureArr = (_obj.picture.split(',')).map(v => {
          let obj = copy(this.thisItem, true)
          obj.isEdit = true
          obj.picture = v
          return obj
        })
      })
    },
    addPicture(val) {
      let obj = {}
      obj.goodId = this.thisItem.goodsBaseId
      obj.goodPicture = val.fileId
      this.saveImgPromise(obj).then(response => {
        if (response) {
          this.searchPicture()
        }
      })
    },
    delPicture(data) {
      confirm('确认删除该图片', '提示', {
        confirmButtonLoading: true,
        dangerouslyUseHTMLString: true,
        showCancelButton: false,
        confirmCallBack: ({confirmButtonLoadingClose, close}) => {
          this.$ajax.post('/ms-fahuobao-order/fhbGoodAdmin/deleteGoodsPic', {
            goodsBaseId: data.goodsBaseId,
            picId: data.picture
          }).then(response => {
            if (response.success) {
              close()
              this.searchPicture()
            }
            confirmButtonLoadingClose()
          }).catch(_ => {
            confirmButtonLoadingClose()
          })
        }
      })
    },
    del(data) {
      confirm('你确定要删除该产品吗？', '提示', {
        confirmButtonLoading: true,
        dangerouslyUseHTMLString: true,
        showCancelButton: false,
        confirmCallBack: ({confirmButtonLoadingClose, close}) => {
          this.$ajax.get('/ms-fahuobao-order/fhbGoodAdmin/deleteGoodById', {
            goodId: data.goodsBaseId
          }).then(response => {
            if (response.success) {
              close()
              this.getProducts()
            }
            confirmButtonLoadingClose()
          }).catch(_ => {
            confirmButtonLoadingClose()
          })
        }
      })
    },
    edit(item) {
      item.isEdit = true
    },
    beforeDestroy() {
      bus.$off('activeMenuValFHB')
    }
  }
}
</script>
<style lang="scss">
  .a-product-show-box {
    width: 184px;
    height: 208px;
    float: left;
    margin: 0px 21px 21px 0px;
    cursor: pointer;
    .product-show-img-box {
      width: 100%;
      height: 178px;
      border: 1px solid #C0CCDA;
      .product-img-b {
        width: 182px;
        height: 148px;
        img {
          width: 100%;
          height: 100%;
        }
      }
      .product-img-name {
        width: 100%;
        text-align: center;
        color: #333;
        background: #f0f1f4;
        white-space: nowrap;
        overflow: hidden;
        text-overflow:ellipsis;
        .el-input__inner {
          height: 28px;
        }
        span {
          display: inline-block;
          width: 154px;
          white-space: nowrap;
          overflow: hidden;
          text-overflow:ellipsis;
          height: 24px;
          line-height: 27.5px;
        }
        .product-img-edit {
          line-height: 28px;
          margin-right: 10px;
        }
        .product-img-edit:hover {
          color: #35C6D4;
        }
      }
      .product-img-check {
        position: absolute;
        cursor: pointer;
        z-index: 20;
        margin: -30px 0px 0px 152px;
        color: #959598;
        font-size: 25px;
      }
      .product-img-checked {
        color: $green;
      }
      .product-img-operation {
        text-align: center;
        height: 28px;
        line-height: 28px;
        .product-img-btn {
          color: $green;
          display: inline-block;
        }
      }
    }
  }
  .noProduct-box {
    text-align: center;
  }
  .product-img-num {
    width: 22px;
    height: 20px;
    text-align: center;
    line-height: 20px;
    font-size: 12px;
    background: #C4C4C4;
    position: absolute;
    cursor: pointer;
    margin: -148px 0px 0px 160px;
  }
</style>
